package com.dana.security.service;

import cn.hutool.core.lang.UUID;
import com.core.constants.CacheConstant;
import com.core.constants.JwtConstant;
import com.dana.redis.service.RedisService;
import com.core.domain.LoginUser;
import com.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class TokenService {
    @Autowired
    private RedisService redisService;

    /**
     * 生成一个唯一id,加上logintoken前缀生成为userKey存入redis
     * @param userId 用户id
     * @param secret 随机盐值
     * @param identity 身份信息
     * @return 生成的token令牌
     */
    public String createToken(Long userId,String secret,Integer identity,String nickName,String headImages){

        //使用UUID生成一个唯一id,并且加上logintoken前缀存储到redis中
        String userKey = UUID.fastUUID().toString();
        //生成jwt令牌并且返回给客户端
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtConstant.LOGIN_LOGIN_ID,userId);
        claims.put(JwtConstant.LOGIN_LOGIN_KEY,userKey);
        String token = JwtUtils.createToken(claims, secret);
        //将用户信息存储到redis中,并且在用户访问的时候jwt不会过期
        //key(logintoken:userKey)
        String tokenKey= getTokenKey(userKey);
        //value:loginUser
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImages);
        //缓存到redis中,并且指定3天过期时间
        redisService.setCacheObject(tokenKey,loginUser,CacheConstant.EXP, TimeUnit.MINUTES);

        return token;
    }

    /**
     * 延长redis中的token有效期
     */
    public void extendToken(Claims claims){
        String userKey = getUserKey(claims);
        if (userKey==null){
            return;
        }
        String tokenKey= getTokenKey(userKey);

        //获取剩余key的有效时间
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire!=null&&expire<CacheConstant.REFRESH_TIME){
            //延长过期时间
            redisService.expire(tokenKey,CacheConstant.EXP,TimeUnit.MINUTES);
        }
    }

    private static String getTokenKey(String userKey) {
        return CacheConstant.LOGIN_TOKEN_KEY + userKey;
    }

    public LoginUser getLoginUser(String token,String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey==null){
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }

    public String getUserKey(String token,String secret){
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims); //获取jwt中的key
    }

    public String getUserKey(Claims claims){
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims); //获取jwt中的key
    }

    public  Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息,拿到用户信息
            if (claims == null) {
                log.info("解析token:{} 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.info("解析token:{} 出现异常", token,e);
            return null;
        }
        return claims;
    }


    public Long getUserId(Claims claims){
        return Long.valueOf(JwtUtils.getUserId(claims));
    }


    public boolean deleteLoginUser(String token,String secret) {
        //在token中解析出userKey
        String userKey = getUserKey(token, secret);
        if (userKey==null){
            return false;
        }
        //获取TokenKey并且删除token
        String tokenKey = getTokenKey(userKey);
        return redisService.deleteObject(tokenKey);
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
